function isElectron() {
  // return false
  // Renderer process
  // eslint-disable-next-line no-undef
  if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
    return true;
  }

  // Main process
  if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {
    return true;
  }

  // Detect the user agent when the `nodeIntegration` option is set to true
  // eslint-disable-next-line no-undef
  if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {
    return true;
  }

  return false;
}

/**
 * electronOpen
 * @param options
 * @return {Promise<unknown>}
 */
function electronOpen(options = {}) {
  return new Promise(resolve => {
    const fs = global.require('fs');
    const remote = global.require('electron').remote;
    remote.dialog.showOpenDialog({
      properties: ['openFile'],
      ...options,
    })
      .then(result => {
        // console.log(result.canceled);
        // console.log(result.filePaths);
        if (!result.canceled) {
          if (result.filePaths && result.filePaths[0]) {
            const buffer = fs.readFileSync(result.filePaths[0]);
            // console.log(buffer)
            resolve(new Blob([buffer]));
          }
        }
      })
      .catch(err => {
        console.log(err);
      });
  });
}

export async function fileOpenJSON5({mimeTypes = []} = {}) {
  let text = '';
  try {
    let blob = null;
    const options = {
      mimeTypes,
    };

    // if (isElectron()) {
    //   blob = await electronOpen(options);
    // } else {
    //   blob = await ZY_EXT.FS.fileOpen(options);
    // }
    blob = await ZY_EXT.FS.fileOpen(options);
    if (blob) {
      text = await blob.text();
      try {
        const obj = ZY.JSON5.parse(text);
        return obj;
      } catch (e) {
        return Promise.reject(
          new Error(`fileOpenJSON5 parse err ${e.message}`, {
            cause: e,
          })
        );
      }
    }
  } catch (e) {
    return Promise.reject(
      new Error(`fileOpenJSON5 select err ${e.message}`, {
        cause: e,
      })
    );
  }
}

export const defineDatetimeFormat = 'YYYY-MM-DD__HH_mm_ss';
export function extZY(ZY) {
  globalThis.ZY2 = {}
  globalThis.ZY2.helpers = {
    parseFloat(v, defaultVal = 0) {
      let r = parseFloat(v);
      if (isNaN(r)) {
        return defaultVal;
      }
      return r
    },
    toDecimal2(x) {
      var f = parseFloat(x);
      if (isNaN(f)) {
        return false;
      }
      var f = Math.round(x * 100) / 100;
      var s = f.toString();
      var rs = s.indexOf('.');
      if (rs < 0) {
        rs = s.length;
        s += '.';
      }
      while (s.length <= rs + 2) {
        s += '0';
      }
      return s;
    }
  }
  globalThis.ZY2.getDownloadFileName = function (prefix, fileName) {
    const d = new Date();
    const time = ZY.Time.formatDateTime(d, defineDatetimeFormat);
    return `${prefix}${fileName}_${time}`
  }
  globalThis.ZY2.fileOpenJSON5 = fileOpenJSON5
}
